package cn.jaychang.demo.auth.server.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 认证中心配置
 * <p>
 * `@EnableAuthorizationServer` 这个注解标注这是一个认证中心
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    /**
     * Security的认证管理器，密码模式需要用到
     */
    private final AuthenticationManager authenticationManager;
    /**
     * 客户端存储策略，这里使用内存方式，后续可以存储在数据库
     */
    private final ClientDetailsService clientDetailsService;
    /**
     * 令牌存储策略
     */
    private final TokenStore tokenStore;

    /**
     * 令牌访问安全约束配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 开启/oauth/token_key验证端口权限访问
                .tokenKeyAccess("permitAll()")
                // 开启/oauth/token_key验证端口权限访问
                .checkTokenAccess("permitAll()")
                // 表示支持client_id和client_secret做登录认证
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("app01")
                .secret(passwordEncoder.encode("sec01"))
                .resourceIds("res01")
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                .scopes("all")
                // 是否需要授权，设置为true则不需要用户点击确认授权直接返回授权码; false则跳转到授权页面
                .autoApprove(false)
                // 授权码模式的回调地址
                .redirectUris("http://www.baidu.com");
    }

    /**
     * 配置令牌访问端点
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // 授权码模式需要的authorizationCodeServices
                .authorizationCodeServices(authorizationCodeServices())
                // 密码模式需要的authenticationManager
                .authenticationManager(authenticationManager)
                // 令牌管理服务，无论哪种模式都需要
                .tokenServices(tokenServices())
                // 仅允许POST提交访问令牌， uri: /oauth/token
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
        ;
    }

    /**
     * 授权码模式的service,使用授权码模式authorization_code必须注入
     *
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }

    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        //
        tokenServices.setClientDetailsService(clientDetailsService);
        // 支持令牌的刷新
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 2);
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 3);
        return tokenServices;
    }
}
